var util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //点击下拉显示
    showView: true,
    //一级分类
    tabs: [],
    category: [],
    detail: {},
    isScroll: true,
    curIndex: -1,
    clickId: 0,
    gc_id: '',
    num: 1,
    store_info: "",
    cart_count: 0,
    sum: 0, //该店铺的总价格
    store_id: "",
    cur_page: 1,
    page_num: 10,
  },
  onLoad: function(options) {
    var that = this;
    that.data.store_id = options.store_id;
    util.postUrl('store/index', {
      store_id: options.store_id,
    }, function(res) {
      if (res.data.code == 200) {
        // 初始化渲染分类页面
        var gc_id = res.data.datas.parent_list[0].gc_id
        //获取右边的列表
        that.getList(gc_id);
        that.setData({
          tabs: res.data.datas.parent_list,
          categoryList: res.data.datas.child_class_list,
          category: res.data.datas.child_class_list[gc_id],
          gc_id: gc_id, //下次再点击分类页面需要用
          store_info: res.data.datas.store_info,
        })
      }
    })
  },
  onShow: function() {
    var that = this;
    // //获取右边的列表
    if (that.data.gc_id) {
      that.getList(that.data.gc_id);
    }
  },
  // 商品分页
  bindscrolltolower() {

  },
  // 点击大分类改变左侧边栏
  tabClick: function (e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var gc_id = that.data.tabs[index].gc_id;
    var category = that.data.categoryList[gc_id];
    if (category) {
      that.setData({
        clickId: index,
        category: category,
        curIndex: -1,
        gc_id: gc_id,
        cur_page: 1,
      })
    } else {
      that.setData({
        clickId: index,
        category: [],
        curIndex: -1,
        gc_id: gc_id,
        cur_page: 1,
      })
    }

    //获取右边的列表
    that.getList(gc_id);
  },
  // 左侧分类点击商品展示
  switchTab(e) {
    var that = this;
    var gc_id = e.currentTarget.dataset.id;
    that.setData({
      curIndex: e.currentTarget.dataset.index,
      gc_id: gc_id,
      cur_page:1,
    })
    that.getList(gc_id);


  },
  // 右侧商品分类接口展示

  //点击减号
  bindMinus: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;
    var item = temp[index].spec_list[spec_index];
    item.num = parseInt(item.num);
    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (item.num - 1 < 0) {
      return;
    }
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          if (item.num - 1 == 0) {
            temp_goods.splice(i, 1);
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
          } else {
            temp_goods[i].quantity = item.num - 1;
            temp_goods[i].goods_num = item.num - 1;
          }
        }
      }
      item.num = item.num - 1;
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);
      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      if (item.num - 1 == 0) {
        util.postUrl("cart/cart_remove", {
          cart_id: item.goods_id,
          del_type: 2,
        }, function(res) {
          if (res) {
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
            wx.setStorageSync("check_list", check_list);
            item.num = item.num - 1;
            that.setData({
              detail: temp
            });
            that.initRed();
          }
        })
      } else {
        util.postUrl('cart/cart_add', {
          goods_id: item.goods_id,
          quantity: item.num - 1,
        }, function(res) {
          if (res) {
            item.num = item.num - 1;
            that.setData({
              detail: temp
            });
            that.initRed();
          } else {}
        })
      }
    }
  },

  /* 点击加号 */
  bindPlus: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;
    var item = temp[index].spec_list[spec_index];
    item.num = parseInt(item.num);
    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num + 1;
          temp_goods[i].goods_num = item.num + 1;
          flag = false;
        }
      }
      if (flag) {
        check_list.push(item.goods_id);
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num + 1,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num + 1,
          goods_price: item.goods_price,
        });
      }
      item.num = item.num + 1;
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);

      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: item.num + 1,
      }, function(res) {
        if (res) {
          if (res.data.code == 400) {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'success',
              duration: 2000
            })
            return;
          }
          if (check_list.indexOf(item.goods_id) == -1) {
            check_list.push(item.goods_id);
          }
          wx.setStorageSync('check_list', check_list);
          console.log(check_list);
          item.num = item.num + 1;
          that.setData({
            detail: temp
          });
          that.initRed();
        } else {}
      })
    }

  },
  /* 输入框事件 */
  bindManual: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;

    var item = temp[index].spec_list[spec_index];
    // var index = e.currentTarget.dataset.index;
    console.log(item);
    var temp_num = parseInt(item.num);
    // 将数值与状态写回
    console.log(e.detail.value)
    if (e.detail.value == '' || e.detail.value == 0) {
      e.detail.value = 1;
    }
    item.num = parseInt(e.detail.value);
    that.setData({
      detail: temp,
    })
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num;
          temp_goods[i].goods_num = item.num;
          flag = false;
        }
      }
      if (flag) {
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num,
          goods_price: item.goods_price,
        });
      }
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: parseInt(e.detail.value),
      }, function(res) {
        if (res) {
          that.initRed();

        } else {
          item.num = temp_num;
          that.setData({
            detail: temp
          });
          that.initRed();
        }
      })
    }

  },
  //点击显示隐藏
  onChangeShowState: function(e) {
    var that = this;
    console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    var temp = that.data.detail;
    if (temp[index].showView) {
      temp[index].showView = false;
    } else {
      temp[index].showView = true;
    }
    that.setData({
      detail: temp,
    })
  },
  //更新购物车气泡数
  initRed: function() {
    var that = this;
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      console.log("temp_goods", temp_goods)
      var cart_count = 0;
      var sum = 0;
      if (temp_goods != '') {
        for (let item of temp_goods) {
          cart_count = cart_count + item.quantity;
          sum = sum + parseInt(item.goods_num) * parseFloat(item.goods_price);
        }
      }
      that.setData({
        cart_count: cart_count,
        sum: sum,
      })
      wx.setTabBarBadge({
        index: 2,
        text: cart_count + "",
      })
      if (cart_count == 0) {
        wx.hideTabBarRedDot({
          index: 2,
        })
      }
    } else {
      util.postUrl('cart/cart_count', {}, function(res) {
        if (res.data.code == 200) {
          that.setData({
            cart_count: res.data.datas.count.goods_total_num,
            sum: res.data.datas.count.goods_total_price,
          })
          wx.setTabBarBadge({
            index: 2,
            text: (res.data.datas.count.goods_total_num + ""),
          })
          if (res.data.datas.count.goods_total_num == 0) {
            wx.hideTabBarRedDot({
              index: 2,
            })
          }
        }
      })
    }

  },
  getList: function(gc_id) {
    var that = this;
    util.postUrl(
      'goods/get_list', {
        gc_id: gc_id,
        cur_page: that.data.cur_page,
        page_num: that.data.page_num,
      },
      function(res) {
        if (res.data.code == 200) {

          var temp = res.data.datas.goods_list;
          if (that.data.cur_page == 1) {
            that.data.detail = [];
          }
          if (temp.length > 0) {
            that.setData({
              cur_page: parseInt(that.data.cur_page) + 1,
            })
          }

          that.initRed();
          var detail = that.data.detail;
          temp = detail.concat(temp);

          for (var i = 0; i < temp.length; i++) {
            if (temp[i].min_goods_price == temp[i].max_goods_price) {
              temp[i].price = temp[i].min_goods_price
            } else {
              temp[i].price = temp[i].min_goods_price + " - ￥" + temp[i].max_goods_price
            }
            for (var j = 0; j < temp[i].spec_list.length; j++) {
              var temp_goods = wx.getStorageSync('temp_goods');
              temp[i].spec_list[j].num = 0;
              if (wx.getStorageSync('token') == '') {
                for (var z = 0; z < temp_goods.length; z++) {
                  if (temp_goods[z].goods_id == temp[i].spec_list[j].goods_id) {
                    temp[i].spec_list[j].num = temp_goods[z].quantity;
                  }
                }
              } else {
                var member_carts = res.data.datas.member_carts;
                var num = member_carts[temp[i].spec_list[j].goods_id];
                if (num) {
                  temp[i].spec_list[j].num = num;
                }
              }
            }
          }
          that.setData({
            detail: temp,
          })
        }
      })
  },
  goCar: function() {
    wx.switchTab({
      url: '../shoppingCar/shoppingCar',
    })
  },
  goSearch: function() {
    var that = this;
    wx.navigateTo({
      url: '../search/search?store_id=' + that.data.store_id,
    })
  },
  // 收藏店铺
  collectStore: function() {
    var that = this;
    util.postUrl('member_favorites/store_add', {
      store_id: that.data.store_info.store_id
    }, function(res) {
      if (res.data.code == 200) {
        var store_info = that.data.store_info;
        store_info.is_favorate = true;
        that.setData({
          store_info: store_info,
        })
        wx.showToast({
          title: '店铺收藏成功',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: res.data.datas.error,
          icon: 'none'
        })
      }
    })
  },
  store_del: function() {
    var that = this;
    var store_list = [];
    store_list.push(that.data.store_info.store_id);
    util.postUrl('member_favorites/store_del', {
      store_id_list: JSON.stringify(store_list),
    }, function(res) {
      if (res.data.code == 200) {
        var store_info = that.data.store_info;
        store_info.is_favorate = false;
        that.setData({
          store_info: store_info,
        })
        wx.showToast({
          title: '店铺取消收藏',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: res.data.datas.error,
          icon: 'none'
        })
      }
    })

  },
  goGoodsDetail: function(e) {
    var item = e.currentTarget.dataset.item;
    item.goods_num = item.num;
    wx.navigateTo({
      url: '../goods-details/goods-details?item=' + JSON.stringify(item),
    })
  },
  //上拉加载
  handlescrolltolower: function() {
    var that = this;
    that.getList(that.data.gc_id);
  }
})